import { Component, Input, OnChanges, OnInit, SimpleChanges } from '@angular/core';

import { NameLabel, Page } from '@core/base';
import { CustomService, Log, LogQuery } from '@core/job/custom';
import { fnIsOnChanged } from '@util/tools';

@Component({
  selector: 'app-custom-log-list',
  templateUrl: './custom-log-list.component.html',
  styleUrls: ['./custom-log-list.component.less']
})
export class CustomLogListComponent implements OnInit, OnChanges {
  @Input() configId?: string;
  @Input() showManagerBtn: boolean = false;

  query: LogQuery = new LogQuery();
  logs: Page<Log> = new Page<Log>();
  taskStates: NameLabel[] = [];

  expandSet = new Set<string>();
  isLoading = false;

  constructor(private customSrc: CustomService) {}

  ngOnChanges(changes: SimpleChanges): void {
    fnIsOnChanged(changes['configId'], value => {
      this.query.configId = value;
      this.loadLog();
    });
  }

  ngOnInit(): void {
    if (this.configId) {
      this.query.configId = this.configId;
    }
    this.loadEnum();
    this.loadLog();
  }

  loadEnum(): void {
    this.customSrc.getEnum().subscribe(data => (this.taskStates = data));
  }

  search(): void {
    this.query.page = 1;
    this.loadLog();
  }

  loadLog(): void {
    this.isLoading = true;
    this.customSrc.getLogPage(this.query).subscribe(data => {
      this.logs = data;
      this.isLoading = false;
    });
  }

  onExpandChange(id: string, checked: boolean): void {
    if (checked) {
      this.expandSet.add(id);
    } else {
      this.expandSet.delete(id);
    }
  }
}
